package com.borun.dao;

import java.util.ArrayList;
import java.util.List;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.borun.bean.Base;
import com.borun.util.DBUtil;

public class BaseDao {

	public boolean addBase(Base base) throws SQLException {
		Connection conn = DBUtil.getConnection();
		String sql = "insert into t_base(basename) values(?)";
		PreparedStatement psmt = conn.prepareStatement(sql);
		psmt.setString(1, base.getBasename());
		return psmt.executeUpdate() > 0;
	}

	public boolean updateBase(Base base) throws SQLException {
		Connection conn = DBUtil.getConnection();
		String sql = "update t_base set basename = ? where baseid = ?";
		PreparedStatement psmt = conn.prepareStatement(sql);
		psmt.setString(1, base.getBasename());
		psmt.setInt(2, base.getBaseid());
		return psmt.executeUpdate() > 0;
	}

	public boolean deleteBase(int baseid) throws SQLException {
		Connection conn = DBUtil.getConnection();
		String sql = "delete from t_base where baseid = ?";
		PreparedStatement psmt = conn.prepareStatement(sql);
		psmt.setInt(1, baseid);
		return psmt.executeUpdate() > 0;

	}

	public Base getBase(int baseid) throws SQLException {

		Base b = null;
		Connection conn = DBUtil.getConnection();
		String sql = "select baseid,basename from t_base where baseid = ?";
		PreparedStatement psmt = conn.prepareStatement(sql);
		psmt.setInt(1, baseid);

		ResultSet rs = psmt.executeQuery();
		while (rs.next()) {
			b = new Base();
			b.setBaseid(rs.getInt("baseid"));
			b.setBasename(rs.getString("basename"));
		}
		return b;
	}

	public List<Base> getBases() throws SQLException {
		Connection conn = DBUtil.getConnection();
		Statement stmt = conn.createStatement();
		ResultSet rs = stmt.executeQuery("select baseid,basename from t_base");
		List<Base> baseList = new ArrayList<Base>();
		Base b = null;
		while (rs.next()) {// 如果对象中有数据，就会循环打印出来
			b = new Base();
			b.setBaseid(rs.getInt("baseid"));
			b.setBasename(rs.getString("basename"));
			baseList.add(b);
		}
		return baseList;
	}
}
